<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.supplierId ? $t('crud.addTitle') : $t('temp.modify')"
    :close-on-click-modal="false"
    :width="dialogWidth"
    @close="refreshCategoryList()"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="dataFormRef"
      :inline="true"
      :model="dataForm"
      :rules="dataRule"
      :label-width="labelWidth"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('shop.supplierName')+':'"
        prop="supplierName"
      >
        <el-input
          v-model="dataForm.supplierName"
          class="input-item"

          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.tel')+':'"
        prop="tel"
      >
        <el-input
          v-model="dataForm.tel"
          class="input-item"

          maxlength="50"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.contactName')+':'"
        prop="contactName"
      >
        <el-input
          v-model="dataForm.contactName"
          class="input-item"

          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.contactTel')+':'"
        prop="contactTel"
      >
        <el-input
          v-model="dataForm.contactTel"
          class="input-item"

          maxlength="50"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.qq')+':'"
        prop="qqNumber"
      >
        <el-input
          v-model="dataForm.qqNumber"
          class="input-item"

          maxlength="20"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.weChatNumber')+':'"
        prop="wxNumber"
      >
        <el-input
          v-model="dataForm.wxNumber"
          class="input-item"

          maxlength="100"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.mailbox')+':'"
        prop="mail"
      >
        <el-input
          v-model="dataForm.mail"
          class="input-item"

          maxlength="100"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.fax')+':'"
        prop="fax"
      >
        <el-input
          v-model="dataForm.fax"
          class="input-item"

          maxlength="100"
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.areaName')+':'"
        class="province"
        prop="province"
      >
        <el-form-item prop="province">
          <el-select
            v-model="dataForm.provinceId"

            :placeholder="$t('tip.select')"
            @change="selectProvince"
          >
            <el-option
              v-for="province in provinceList"
              :key="province.areaId"
              :label="province.areaName"
              :value="province.areaId"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="city">
          <el-select
            v-model="dataForm.cityId"

            :placeholder="$t('tip.select')"
            @change="selectCity"
          >
            <el-option
              v-for="city in cityList"
              :key="city.areaId"
              :label="city.areaName"
              :value="city.areaId"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="area">
          <el-select
            v-model="dataForm.areaId"

            :placeholder="$t('tip.select')"
          >
            <el-option
              v-for="area in areaList"
              :key="area.areaId"
              :label="area.areaName"
              :value="area.areaId"
            />
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item
        :label="$t('address.detailed')+':'"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          class="addr-input"

          maxlength="1000"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.supplierCategoryName')+':'"
        prop="name"
      >
        <div style="display: flex">
          <el-form-item prop="name">
            <el-select
              v-model="dataForm.supplierCategoryId"

              clearable
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="category in categoryList"
                :key="category.supplierCategoryId"
                :label="category.name"
                :value="category.supplierCategoryId"
                :disabled="category.status === 0"
              />
            </el-select>
          </el-form-item>
          <!--新建/刷新-->
          <div class="create-refresh-btn">
            <div
              class="default-btn text-btn"
              @click.stop="onAddOrUpdate()"
            >
              {{ $t('admin.newConstruction') }}
            </div>
            <el-divider direction="vertical" />
            <div
              class="default-btn text-btn"
              @click="listCategory()"
            >
              {{ $t('admin.refresh') }}
            </div>
          </div>
        </div>
      </el-form-item>
      <div />
      <el-form-item
        :label="$t('product.status')+':'"
        prop="status"
      >
        <div>
          <el-radio
            v-model="dataForm.status"
            :label="1"
          >
            {{ $t("groups.startUsing") }}
          </el-radio>
          <el-radio
            v-model="dataForm.status"
            :label="0"
          >
            {{ $t("publics.disable") }}
          </el-radio>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span

        class="dialog-footer"
      >
        <div
          class="default-btn"
          @click="visible = false"
        >{{ $t("crud.filter.cancelBtn") }}</div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >{{ $t("crud.filter.submitBtn") }}</div>
      </span>
    </template>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
    />
  </el-dialog>
</template>

<script setup>
import { setDialogWidth, widthChange } from '@/utils/setDialogWidth'
import { isMobile, isPhone, isPhoneStar, isEmail } from '@/utils/validate'
import AddOrUpdate from './supplierCategory-add-or-update.vue'
import { ElMessage } from 'element-plus'
import { reactive } from 'vue'

const dataFormRef = ref(null)
const validateSupplierName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shop.supplierName') + $t('publics.noNull')))
  } else {
    callback()
  }
}

const validMobile = (rule, value, callback) => {
  if (value == null || value === '') {
    dataFormRef.value.clearValidate('contactTel')
    callback()
  } else if (dataForm.value.contactTel) {
    const mobile = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
    if (mobile.test(value)) {
      callback()
    } else {
      callback(new Error($t('language') === '简体中文' ? '请输入正确的手机号' : 'Please enter valid mobile'))
    }
  } else if (!isMobile(value)) {
    callback(new Error($t('language') === '简体中文' ? '请输入正确的手机号' : 'Please enter valid mobile'))
  } else {
    callback()
  }
}

const validMail = (rule, value, callback) => {
  if (value == null || value === '') {
    dataFormRef.value.clearValidate('mail')
    callback()
  } else if (!isEmail(value)) {
    callback(new Error($t('shopProcess.emailErrorTips')))
  } else {
    callback()
  }
}

const validPhone = (rule, value, callback) => {
  if (value == null || value === '') {
    dataFormRef.value.clearValidate('tel')
    callback()
  } else if (dataForm.value.supplierId ? !isPhoneStar(value) : !isPhone(value)) {
    callback(new Error($t('language') === '简体中文' ? '请输入正确的座机号' : 'Please enter valid phone number'))
  } else {
    callback()
  }
}
const validateQq = (rule, value, callback) => {
  if (value == null || value === '') {
    dataFormRef.value.clearValidate('qqNumber')
    callback()
  } else if (!/[1-9][0-9]{4,14}/.test(value)) {
    callback(new Error($t('language') === '简体中文' ? '请输入正确的QQ号' : 'Please enter valid qq'))
  } else {
    callback()
  }
}

const validateWx = (rule, value, callback) => {
  if (value == null || value === '') {
    dataFormRef.value.clearValidate('wxNumber')
    callback()
  } else if (!/^[a-zA-Z][a-zA-Z\d_-]{5,19}$/.test(value)) {
    callback(new Error($t('language') === '简体中文' ? '请输入正确的微信号' : 'Please enter valid wx'))
  } else {
    callback()
  }
}

const emit = defineEmits(['refreshDataList', 'refreshCategoryList'])

const visible = ref(false)
const addOrUpdateVisible = ref(false)
const dataForm = ref({
  refundAddrId: null,
  supplierId: null,
  shopId: null,
  supplierName: null,
  tel: null,
  provinceId: null,
  province: null,
  cityId: null,
  city: null,
  areaId: null,
  area: null,
  addr: null,
  contactName: null,
  contactTel: null,
  qqNumber: null,
  wxNumber: null,
  mail: null,
  fax: null,
  createTime: null,
  updateTime: null,
  status: 1,
  categoryName: null,
  supplierCategoryId: null
})
const provinceList = ref([])
const categoryList = ref([])
const cityList = ref([])
const areaList = ref([])
const dataRule = {
  supplierName: [
    { required: true, message: $t('shop.supplierName') + $t('publics.noNull'), trigger: 'blur' },
    { validator: validateSupplierName, trigger: 'blur' }
  ],
  tel: [
    { validator: validPhone, trigger: ['blur'] }
  ],
  contactTel: [
    { validator: validMobile, trigger: ['blur'] }
  ],
  mail: [
    { validator: validMail, trigger: ['blur'] }
  ],
  qqNumber: [
    { validator: validateQq, trigger: ['blur'] }
  ],
  wxNumber: [
    { validator: validateWx, trigger: ['blur'] }
  ]
}
const _them = reactive({
  dialogWidth: ''
})
const dialogWidth = toRef(_them, 'dialogWidth')
const defWidth = 815
const labelWidth = localStorage.getItem('bbcLang') === 'en' ? '130px' : '100px'

onMounted(() => {
  dialogWidth.value = setDialogWidth(defWidth)
  widthChange(_them, defWidth)
})

const init = (supplierId) => {
  dataForm.value.supplierId = supplierId || 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    cityList.value = []
    areaList.value = []
    dataForm.value.provinceId = null
    dataForm.value.cityId = null
    dataForm.value.areaId = null
    dataForm.value.supplierCategoryId = null
  })
  listAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  listCategory()

  if (dataForm.value.supplierId) {
    http({
      url: http.adornUrl('/supplier/supplier/info/' + dataForm.value.supplierId),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      listAreaByParentId(data.provinceId).then(({ data }) => {
        cityList.value = data
      })
      listAreaByParentId(data.cityId).then(({ data }) => {
        areaList.value = data
      })
    })
  }
}
defineExpose({ init })

// 新增 / 修改
const addOrUpdateRef = ref(null)
const onAddOrUpdate = () => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init()
  })
}
// 表单提交
const onSubmit = () => {
  getAreaName()
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      http({
        url: http.adornUrl('/supplier/supplier'),
        method: dataForm.value.supplierId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}
const getCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
// 选择省
const selectProvince = (val) => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  dataForm.value.areaId = null
  dataForm.value.area = ''
  areaList.value = []
  // 获取城市的select
  // cityList.value = getCurrentChild(provinceList.value, val)
  const { curNode, areas } = getCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
}
// 选择市
const selectCity = (val) => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  // 获取区的select
  // areaList.value = getCurrentChild(cityList.value, val)
  const { curNode, areas } = getCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}
const listAreaByParentId = (pid) => {
  let paramData = {}
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { pid }
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}
/**
   * 通过省市区id,得到省市区名称
   */
const getAreaName = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
}
const listCategory = () => {
  http({
    url: http.adornUrl('/supplier/supplierCategory/list'),
    method: 'get',
    params: {
      isAll: 1
    }
  }).then(({ data }) => {
    categoryList.value = data
  })
}
const refreshCategoryList = () => {
  emit('refreshCategoryList')
}

</script>
<style lang="scss" scoped>
.input-item {
  width: 240px;
}
.addr-input {
  width: 600px;
}
.province :deep(.el-form-item){
  width:174px ;
  margin-right: 20px
}
</style>
